package com.raymond.thread.manager.scheduled;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledFuture;

/**
 * 定时线程使用cron表达式管理
 * 下一步设想:
 * 做一个修改和删除,动态修改定时任务
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2020-11-09 17:19
 */
@Component
public class ScheduleTaskUtils {
    private final ThreadPoolTaskScheduler threadPoolTaskScheduler;

    public ScheduleTaskUtils(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }

    /**
     * 添加定时任务，如果任务名重复则抛出异常
     * @param task 任务
     * @param cron 定时器
     */
    public ScheduledFuture<?> addTask(Runnable task, final String cron) {
        return threadPoolTaskScheduler.schedule(task, triggerContext -> {
            CronTrigger cronTrigger = new CronTrigger(cron);
            return cronTrigger.nextExecutionTime(triggerContext);
        });
    }
}
